package com.neusoft.neuiotms.dcom.repository.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import com.neusoft.bizcore.web.jpa.repository.AbstractRepository;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.model.Institutions;
import com.neusoft.neuiotms.dcom.model.QInstitutions;
import com.neusoft.neuiotms.dcom.model.QResidentUser;
import com.neusoft.neuiotms.dcom.repository.CustomizedInstitutionsRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.jpa.impl.JPAQuery;

public class CustomizedInstitutionsRepositoryImpl extends AbstractRepository
        implements CustomizedInstitutionsRepository {

    @Override
    public List<Institutions> index(final Searchable searchable) {
        final QInstitutions qInstitutions = QInstitutions.institutions;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Institutions> query = this.query().selectFrom(qInstitutions);
        query.where(where);
        return query.fetch();
    }

    @Override
    public Page<Institutions> page(final Searchable searchable, final Pageable pageable) {
        final QInstitutions qInstitutions = QInstitutions.institutions;
        final QResidentUser qResidentUser = QResidentUser.residentUser;
        final BooleanBuilder where = this.buildWhere(searchable);
        final JPAQuery<Institutions> query = this.query().selectFrom(qInstitutions);
        if (!StringUtils.isEmpty(searchable.getStrValue("resident"))) {
            query.leftJoin(qResidentUser).on(qInstitutions.id.eq(qResidentUser.institutions.id));
            where.and(super.equalsStr(qResidentUser.username, searchable, "resident"));
        }

        query.where(where);
        return super.search(query, pageable);
    }

    @Override
    protected Class<?> getModelClass() {
        return Institutions.class;
    }

    private BooleanBuilder buildWhere(final Searchable searchable) {
        final BooleanBuilder where = new BooleanBuilder();
        final QInstitutions qInstitutions = QInstitutions.institutions;

        if (!StringUtils.isEmpty(searchable.getStrValue("name"))) {
            where.and(super.containsStr(qInstitutions.name, searchable, "name"));
        }

        return where;
    }

}
